<template>
    <div class="wrapper setting-module">
        <el-row>
            <div class="top-edit">
                <span class='setting-left-btn'>
                    <el-button size="small" @click='addMoudle' icon="el-icon-plus">添加模块</el-button>
                    <el-button @click='reFresh' size="small"><i class="fa fa-refresh"></i> 刷新</el-button>
                </span>
            </div>
        </el-row>
        <el-row>
            <el-table v-model="powerModuleList" :data="powerModuleList" stripe>
                <!-- <el-table-column type="selection" width="55"></el-table-column> -->
                <el-table-column type="index" width="80"></el-table-column>
                <el-table-column label="模块名称" width="200" className="asdm">
                    <template scope="scope"><div>{{scope.row.name}}</div></template>
                  <!-- <template scope="scope"><div class='name-btn' @click="savePowerModule(scope.row,'editModule')">{{scope.row.name}}</div></template> -->
                </el-table-column>
                <el-table-column label="包含权限" width="400" className="asdm">
                    <template scope="scope">
                      <!-- <el-button  @click="savePowerModule(scope.row,'addpower')" size="mini" type="primary" icon="el-icon-plus"></el-button> -->
                      <span v-for="(itme,i) in scope.row.modulResList" :key="i" @click="editPowerItem(itme)" ><el-tag  type="primary" close-transition>{{itme.name}}</el-tag></span>
                        
                        <!-- <el-tag v-for="itme in scope.row.api" type="primary" close-transition>{{itme.name}}</el-tag> -->
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="备注" min-width="160"></el-table-column>
                <el-table-column fixed="right" label="操作" width="160" className="asdm" align="center">
                    <template scope="scope">
                        <el-button @click="savePowerModule(scope.row,'editModule')" size="mini" class="el-button--primary" icon="el-icon-edit">编辑</el-button>
                        <el-button @click="delectPowerModule(scope.row)" class="el-button--danger" size="mini" icon="el-icon-delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <div class="pagination">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentModulePage"
                    :page-sizes="pageSizes"
                    :page-size="50"
                    layout="total, sizes,prev, pager, next, jumper"
                    :total="totalModuleCount">
            </el-pagination>
        </div>

        <!--添加模块摸态框-->
        <el-dialog @close="handleDialogClose" title="添加模块" :visible.sync="importVisible" class="module-dialog" >
            <div class="module-opera" >
                <el-form :model="moduleAdd" :rules="rules" ref="moduleAdd" label-width="120px">
                    <el-form-item prop="moduleName" label="模块名称:">
                        <el-input v-model.trim="moduleAdd.moduleName" ></el-input>
                    </el-form-item>
                    <el-form-item prop="moduleInfo" label="模块备注:" style="margin-top:20px;">
                        <el-input v-model.trim="moduleAdd.moduleInfo" ></el-input>
                    </el-form-item>
                    <div class="bottom-btn">
                        <el-button @click="submitAddMoudle('add')" size="small" type="primary" icon="el-icon-upload2">保存</el-button>
                        <el-button @click="importVisible = false" size="small" type="warning" icon="el-icon-close">取消</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>

        <!--修改模块-->
        <el-dialog @close="handleDialogClose" title="模块编辑" :visible.sync="editVisible" class="module-dialog" >
            <div class="module-opera m-opera side-center">
                <el-form v-show="operaType =='editModule'" :model="moduleAdd" :rules="rules" ref="moduleAdd" label-width="100px" class="module-form">
                    <el-form-item prop="moduleName" label="模块名称:">
                        <el-input v-model.trim="moduleAdd.moduleName" ></el-input>
                    </el-form-item>
                    <el-form-item prop="moduleInfo" label="模块备注:">
                        <el-input v-model.trim="moduleAdd.moduleInfo" ></el-input>
                    </el-form-item>
                </el-form>

                <el-form :model="editModule" :rules="rules2" ref="editModule" label-width="100px">
                    <div v-show="operaType =='editModule'" class="power-list">
                        <p class="power-list-title">已有权限：<span v-if="!modulResList.length">--</span></p>
                        <el-tag v-for='(item,i) in modulResList' :key="i" @close='delPowerItem(item,i)' :closable="true" type="primary">{{item.name}}</el-tag>
                    </div>
                    <el-collapse class='model-collapse' v-model="activeNames">
                        <el-collapse-item  title="添加新权限" name="1">
                            <el-form-item prop="name" label="权限名称:">
                                <el-input class='inner-input' v-model.trim="editModule.name" auto-complete="off"></el-input>
                            </el-form-item>
                            <el-form-item prop="url" label="权限URL:">
                                <el-input class='inner-input' v-model.trim="editModule.url" auto-complete="off"></el-input>
                            </el-form-item>
                            <el-form-item prop="minUseLevel" label="限制等级:">
                                <el-select v-model="editModule.minUseLevel" placeholder="使用者等级限制">
                                    <el-option v-for="item in levelData"  :label="item.name" :value="item.value" :key="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="maxApproveLevel" label="审批等级:">
                                <el-select v-model="editModule.maxApproveLevel" placeholder="审批人等级限制:">
                                    <el-option v-for="item in levelData" :key="item.value" :label="item.name" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="权限备注:">
                                <el-input class='inner-input' v-model.trim="editModule.description" auto-complete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="">
                                <el-button @click="addNewItem('add')" :disabled="!editModule.name || !editModule.url" type="primary" size="small" icon="el-icon-plus">添加</el-button>
                            </el-form-item>
                        </el-collapse-item>
                    </el-collapse>

                    <div class="bottom-btn">
                        <el-button @click="updateMoudle()" size="small" type="primary" icon="el-icon-upload2">保存</el-button>
                        <el-button @click="editVisible = false" size="small" type="warning" icon="el-icon-close">取消</el-button>
                    </div>
                </el-form>


            </div>
        </el-dialog>

        <!--*****************修改权限************-->
        <el-dialog @close="handleDialogClose" title="权限编辑" :visible.sync="editPowerVisible" class="module-dialog" >
            <div class="module-opera p-opera side-center">
                <el-form :model="editModule" :rules="rules2" ref="editModule" :inline="true" label-width="120px">
                    <el-form-item prop="name" label="权限名称:">
                        <el-input class='inner-input' v-model.trim="editModule.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="url" label="权限URL:">
                        <el-input class='inner-input' v-model.trim="editModule.url" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="minUseLevel" label="限制等级:">
                        <el-select v-model="editModule.minUseLevel" placeholder="使用者等级限制">
                            <el-option v-for="item in levelData" :key="item.value" :label="item.name" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="maxApproveLevel" label="审批等级:">
                        <el-select v-model="editModule.maxApproveLevel" placeholder="审批人等级限制:">
                            <el-option v-for="item in levelData" :key="item.value" :label="item.name" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="权限描述:">
                        <el-input class='inner-input' v-model.trim="editModule.description" auto-complete="off"></el-input>
                    </el-form-item>
                    <div class="bottom-btn">
                        <el-button @click="addNewItem('uptate')" type="primary" icon="el-icon-upload2">保存</el-button>
                        <el-button @click="editPowerVisible = false" type="warning" icon="el-icon-close">取消</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Vue from 'vue';
    import axios from '~/plugins/axios'
    import * as types from '../../../store/mutation-types/power-setting/index';
    import { mapGetters, mapActions, mapMutations} from 'vuex';
    import { Row, Col, Form, FormItem, Input, ButtonGroup, Button, Table, TableColumn,Pagination,Dialog,Tag,Tooltip,Collapse,CollapseItem,Select,Option} from 'element-ui'
    import { Icon,MessageBox,Message} from 'element-ui';
    import { ACTIVEINDEX } from '../../../store/mutation-types/left-menu/index';

    Vue.use(Row);
    Vue.use(Col);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Input);
    Vue.use(Button);
    Vue.use(Table);
    Vue.use(TableColumn);
    Vue.use(Pagination);
    Vue.use(Icon);
    Vue.use(Dialog);
    Vue.use(Tag);
    Vue.use(Tooltip);
    Vue.use(Collapse);
    Vue.use(CollapseItem);
    Vue.use(Select);
    Vue.use(Option);

    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;
    export default {
        head(){
            return {
                title: "权限模块管理"
            }
        },
        data(){
            return {
                tabName: '权限模块管理',
                options:[{"label":'1',"value":'1',}],
                selectIndex : [],
                singalIndex : [],
                team:[],
                activeNames:[],
                pageSize:50,
                pageSizes: [10,30,50],
                importVisible:false,
                editVisible:false,
                editPowerVisible:false,
                editorItemId:'',
                operaType:'editModule',
                modulResList:[],
                moduleAdd:{
                    moduleName:'',
                    powerValue:'',
                    moduleInfo:'',
                    appModuleId:''
                },
                moduleAdd2:{
                    moduleName:'',
                    powerValue:'',
                    moduleInfo:'',
                    appModuleId:''
                },
                editModule:{
                    name:'',
                    url:'',
                    targetId:'',
                    description:'',
                    minUseLevel:'0',
                    maxApproveLevel:'0',
                    appModuleId:''
                },
                defaultProps: {
                    children: 'children',
                    label: 'text'
                },
                rules:{
                    moduleName: [{ required: true, message: '请输入模块名称', trigger: 'blur' }],
                    moduleInfo: [{ required: false, message: ' ', trigger: 'blur' }]
                },
                rules2:{
                    name: [{ required: true, message: ' ', trigger: 'blur' }],
                    url: [{ required: true, message: ' ', trigger: 'blur' }],
                    minUseLevel: [{ required: false, message: ' ', trigger: 'blur' }],
                    maxApproveLevel: [{ required: false, message: ' ', trigger: 'blur' }]
                },
                levelData:[
                    {name:'0',value:'0'},
                    {name:'1',value:'1'},
                    {name:'2',value:'2'},
                    {name:'3',value:'3'},
                    {name:'4',value:'4'},
                    {name:'5',value:'5'},
                    {name:'6',value:'6'},
                    {name:'7',value:'7'},
                    {name:'8',value:'8'},
                    {name:'9',value:'9'},
                    {name:'10',value:'10'}
                ],
                regions: [],
                'check-strictly':true,
                'highlight-current':true,
                props: {
                    label: 'name',
                    children: 'zones'
                },
                count: 1
            }
        },

        computed : {
            ...mapGetters({
                'powerModuleList' : 'getPowerModuleList',
                'totalModuleCount' : 'getPowerModuleTotalCount',
                'currentModulePage' : 'getPowerModuleCurrentPage',
                'pageTabsList': 'getPageTabsList'
            })
        },
        created(){
            //appId 应用系统id，crm默认为1
            this.getPowerModuleData({appId:1,page: 1 , size :this.pageSize});
            //pageTab
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
        },

        methods:{
            updateMoudle(){
                this.submitAddMoudle('uptate');
                if(this.activeNames.length){
                    // this.addNewItem('add')
                }
            },

          //刷新
          reFresh(){this.getPowerModuleData({appId:1,page: 1 , size :this.pageSize})},
          //修改权限item
          editPowerItem(item){
              this.editPowerVisible = true;
              this.editModule = {
                    name: item.name,
                    url: item.url,
                    id: item.id,
                    targetId: item.targetId,
                    description: item.description,
                    minUseLevel: item.minUseLevel || 0,
                    maxApproveLevel: item.maxApproveLevel || 0,
                    appModuleId: item.appModuleId
                };
              //数字转字符串
              this.editModule.minUseLevel+='';
              this.editModule.maxApproveLevel+='';
              if(this.editModule.status)delete this.editModule.status
          },

          //修改模块--摸态框
          savePowerModule(row,operaType){
              this.operaType = operaType;
              if(this.operaType == 'editModule'){
                this.activeNames = [];
              }else{
                this.activeNames = ['1'];
              }
              this.editVisible = true;
              this.moduleAdd.moduleName = row.name;
              this.moduleAdd.moduleInfo = row.description;
              this.moduleAdd.appModuleId = row.id;
              this.editModule.appModuleId = row.id;
              this.modulResList = row.modulResList||[];
          },

          //添加、修改权限
          addNewItem(evenType){
              if(this.editModule.minUseLevel>this.editModule.maxApproveLevel){
                  this.$message({ type: 'error', message: '限制等级需小于等于(≤)审批等级' });
                  return
              }
              this.$refs['editModule'] && this.$refs['editModule'].validate((valid) => {
                if (valid) {
                  this.$store.dispatch('addPowerItem',this.editModule)
                    .then((res)=>{
                      if(res.data.code ==0 && res.data.successed){
                           // if(res.data.data.code && res.data.data.code == 103){
                           //     this.$message({ type: 'error', message: '无权限操作该板块！' }); 
                           //     return;
                           //  }
                          let item = res.data.data;
                          if(evenType =='add') {
                              this.$store.commit('POWER_ITEM_LIST_ADD', {list:item});
                              //this.getPowerModuleData({appId:1,page: this.currentModulePage , size :this.pageSize});
                              this.$message({ type: 'success', message: "添加成功" });
                              if(this.operaType == 'addpower'){
                                this.editVisible = false;
                              }
                          }else if(evenType =='uptate'){
                              //this.$store.commit('POWER_ITEM_LIST_UPDATE', {list:item});
                              this.getPowerModuleData({appId:1,page: this.currentModulePage , size :this.pageSize});
                              this.$message({ type: 'success', message: "修改成功！" });
                              this.editPowerVisible = false;
                          }
                          this.editModule = {name:'', url:'', targetId:'', description:'', minUseLevel:'0', maxApproveLevel:'0', appModuleId:this.editModule.appModuleId}
                      }else{
                          this.$message({ type: 'error', message: res.data.message.slice(0,30) });
                      }
                    })
                } else {
                    return false;
                }
              })
          },

          //添加模块摸态框
          addMoudle(){
              this.importVisible = true;
              this.moduleAdd.moduleName = '';
              this.moduleAdd.moduleInfo = '';
              this.moduleAdd.appModuleId = '';
          },

          //删除powerItem
          delPowerItem(item,i){
              this.$confirm('确定要删除权限：'+item.name+'吗?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(() => {
                  let params = {
                     moduleId : item.appModuleId,
                     powerId : item.id,
                   }
                  this.$store.dispatch('delPowerItem', params).then((res)=>{
                    if(res.data.code==0){
                        // if(res.data.data && res.data.data && res.data.data.code && res.data.data.code == 103){
                        //    this.$message({ type: 'error', message: '无权限操作该板块！' }); 
                        //    return;
                        // }
                      //this.$store.commit('POWER_ITEM_LIST_DEL', {list:params});
                      this.modulResList.splice(i, 1)
                    }else{
                        this.$message({ type: 'error', message: res.data.message.slice(0,30) });
                    }
                   });
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });
              });
          },

          //关闭摸态框--初始化数据
          handleDialogClose(){
              this.moduleAdd = this.moduleAdd2;
              this.editModule = {name:'', url:'', targetId:'', description:'', minUseLevel:'0', maxApproveLevel:'0', appModuleId:this.editModule.appModuleId};
              this.importVisible = false;
              this.editVisible = false;
              this.editPowerVisible = false;
          },

          //添加新模块/修改模块
          submitAddMoudle(evenType){
              this.$refs['moduleAdd'] && this.$refs['moduleAdd'].validate((valid) => {
                  if (valid) {
                      let preload = {
                          appId :1,//默认1 代表crm
                          id : this.moduleAdd.appModuleId,//如果id为空，则新增
                          name : this.moduleAdd.moduleName,
                          description : this.moduleAdd.moduleInfo
                      }
                      this.$store.dispatch('addPowerModule',preload).then((res)=>{
                          if(res.data.code == 0 && res.data.successed){
                            // if(res.data.data && res.data.data && res.data.data.code && res.data.data.code == 103){
                            //    this.$message({ type: 'error', message: '无权限操作该板块！' }); 
                            //    return;
                            // }
                              if(evenType == 'add'){
                                  let item = res.data.data;
                                  item.modulResList = [];
                                  this.$store.commit('POWER_MOUDLE_ADD', {list:item});
                                  this.getPowerModuleData({appId:1,page: this.currentModulePage , size :this.pageSize});
                                  this.$message({ type: 'success', message: '添加成功！' });
                                  this.importVisible = false;
                              }else{
                                  this.$store.commit('POWER_MOUDLE_UPDATE', {list:preload});
                                  this.getPowerModuleData({appId:1,page: this.currentModulePage , size :this.pageSize});
                                  this.$message({ type: 'success', message: '更新成功！' });
                                  this.editVisible = false;
                              }
                          }else{
                            this.$message({ type: 'error', message: res.data.message.slice(0,30)});
                          }
                      });
                  } else {
                      return false;
                  }
              })
          },

          //删除模块
          delectPowerModule(row){
              if(row.modulResList.length>0){
                  this.$confirm('对不起，该模块下仍有权限，无法删除！', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                  }).then(() => {
                    // this.savePowerModule(row,'editModule')
                    return;
                  }).catch(() => {});
                  return;
              };
              //判断模块下是否还有权限，如果有则不能删除
              this.$confirm('确定要删除权限模块'+row.name+'吗?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(() => {
                  this.$store.dispatch('delPowerModule',{id : row.id})
                  .then((res)=>{
                    if(res.data.code == 0){
                        // if(res.data.data && res.data.data && res.data.data.code && res.data.data.code == 103){
                        //    this.$message({ type: 'error', message: '无权限操作该板块！' }); 
                        //    return;
                        // }
                        this.$message({ type: 'success', message: res.data.message });
                        this.$store.commit('POWER_MOUDLE_LIST_DEL', {id:row.id});
                      }else{
                        this.$message({ type: 'error', message: res.data.message.slice(0,30) });
                      }
                  });
              }).catch(() => {});
          },

          //分页处理
          handleSizeChange(index){
            this.pageSize = index
            this.getPowerModuleData({appId:1, page:1, size:this.pageSize})
          },
          handleCurrentChange(index){

            this.getPowerModuleData({appId:1, page:index, size:this.pageSize})
          },

          //获取模块列表
          getPowerModuleData(option){
              this.$store.dispatch('powerModuleList',option);
          }
      }
    }

</script>
<style lang="scss">
.el-table .asdm>.cell{
            padding: 0px;
        }
  .setting-module{
        .title{
            float: left;
            margin-right: 120px;
        }
        .tips-title{
            padding:10px;
            border:1px solid #ff4949;
            color: #ff4949;
            box-sizing:border-box;
            border-radius:4px;
        }
        .top-edit{
            padding: 10px 10px;
            text-align: left;
            border:1px solid #DFE6EC;
        }
        .name-btn{
          cursor: pointer;
          color: #4db3ff;
        }
        .name-btn:hover{
          font-weight:800;
        }

        .pagination{
            margin-top: 10px;
        }

        .el-tag{
            margin-left: 3px;
            margin-bottom: 3px;
            cursor: pointer;
        }
        .el-tag:hover{
            border-color: rgba(32,160,255,.7);
        }

        .module-dialog{
            .module-title{
                margin: 0;
                width: 185px;
                height: 36px;
                padding-left:5px;
                border:1px solid #BFCBD9;
                border-radius:4px;
            }
            .power-list{
                margin-bottom: 10px;
                padding-left: 25px;
                .power-list-title{
                    float: left;
                    text-align: left;
                    height: 20px;
                    line-height: 20px;
                    margin:0;
                    color: #48576a;
                }
            }
            .power-list:after{
                content:".";
                display:block;
                height:0;
                clear:both;
                visibility:hidden;
            }
            .el-dialog--small{
                min-width: 600px;
                width: 35%;
            }
            .el-dialog__body{
                padding: 5px;
            }
            .el-dialog__body:after{
                content:".";
                display:block;
                height:0;
                clear:both;
                visibility:hidden;
            }
            .el-dialog__footer{
                text-align: center;
            }
            .top-panel{
                height: 30px;
                line-height: 30px;
                font-weight: bold;
            }
            .m-opera{
                .el-button{
                    //width: 100%;
                }
                .el-select{
                    width: 100%;
                }
            }
            .p-opera{
                .el-select{
                    width: 190px;
                }
            }
            .module-opera{
                .el-form{
                    width: 360px;
                    margin: 0 auto;
                .team-input{
                    width: 130px;
                }
                .inline-input{
                    width: 160px;
                }
                .power-btn{
                    padding-left:120px;
                }
                }
                .el-form-item{
                    margin-bottom: 10px;
                    width: 100%;
                }

                .model-collapse{
                    margin-bottom: 20px;
                    padding-left: 25px;
                    border:0;
                    .el-collapse-item{
                        .el-collapse-item__header{
                          background-color: #f7ba2a;
                          color: #fff;
                          border-radius: 4px 4px 0 0;
                        }
                        .el-collapse-item__header:hover{
                          background-color: #f9c855;
                        }
                        .el-collapse-item__content{
                          border:1px solid #DFE6EC;
                          border-top:0;
                        }
                    }
                    
                }
            }
            .side-center{
                margin: 0 auto;
                width: 360px;
            }
        }
        .bottom-btn{
            width:100%;
            display:table;
            text-align:center;
            margin: 20px 0;
        }
    }

    

    
    
</style>